package com.eureka.eurekaserviceinvoker.service;

import com.eureka.eurekaserviceinvoker.entity.Person;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Created by earl on 2018/5/2.
 */
@Component
public class PersonService {

    @Autowired
    private RestTemplate restTemplate;


    @HystrixCommand(
            //忽略NullPointerException
            ignoreExceptions = {NullPointerException.class},
            //异常回退方法
            fallbackMethod = "getPersonFallback",
            //分组key，使用的线程池key,隔离机制key
            groupKey = "Mygroup", threadPoolKey = "myCommonPool",commandKey = "MyCommandKey",
            commandProperties = {
                //条件阈值，设置1秒
                @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value="1000")
            },
            threadPoolProperties = {
                //线程池大小
                @HystrixProperty(name = "coreSize",value = "1")
            }
    )
    public Person getPerson(Long id) {
        //正确的地址
//        Person p = restTemplate.getForObject("http://eureka-service-provider/provider/person/{id}", Person.class, id);
        //错误的地址，为了测试断路器
        Person p = restTemplate.getForObject("http://eureka-service-provider/provider/persontest/{id}", Person.class, id);
        return p;
    }

    //回退方法，这里的参数、参数类型要和getPerson一致
    public Person getPersonFallback(Long id){
        Person p = new Person();
        p.setId(0L);
        p.setName(" fallBack Name ");
        return p;
    }









}
